package com.sy.socket.tcp;

import java.io.*;
import java.net.*;

public class Client {

    public static void main(String[] args) throws IOException {
        // 初始化socket
        Socket socket = new Socket();
        // 超时时间
        socket.setSoTimeout(3000);
        // 连接本地，端口2000，超时3000ms
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000), 3000);
        System.out.println("向服务器发送连接");
        System.out.println("客户端地址：" + socket.getLocalAddress() + "port" + socket.getLocalPort());
        System.out.println("服务器地址：" + socket.getInetAddress() + "port" + socket.getPort());

        try {
            // 发送数据
            todo(socket);
        } catch (Exception e) {
            System.out.println("异常关闭");
        }

        // 关闭连接套接字
        socket.close();
        System.out.println("客户端退出");
    }


    /**
     * 发送数据
     * @param client
     * @throws IOException
     */
    private static void todo(Socket client) throws IOException {
        // 获取键盘的输入流
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));

        // 获取客户端socket的输出流
        OutputStream outputStream = client.getOutputStream();
        // 转换为打印流
        PrintStream socketPrintStream = new PrintStream(outputStream);

        // 获取socket的输入流，转换为BufferedReader
        InputStream inputStream = client.getInputStream();
        BufferedReader socketBufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        boolean flag = true;
        do {
            // 从键盘读取一行
            String s = input.readLine();
            // 发送到服务器
            socketPrintStream.println(s);


            // 从服务器读取一行
            String echo = socketBufferedReader.readLine();
            if("bye".equalsIgnoreCase(echo)){
                flag = false;
            } else {
                // 打印读取回来的数据
                System.out.println(echo);
            }
        } while (flag);

        // 释放流资源
        socketPrintStream.close();
        socketBufferedReader.close();
    }

}
